<template>
	<Upload 
		:action="action" 
		:show-upload-list="showUploadList" 
		:accept="accept" 
		:headers="headers" 
		:data="data"
		:before-upload="beforeUpload"
		:on-success="onSuccess" 
		:on-error="onError">
		<Button icon="ios-cloud-upload-outline">{{label}}</Button>
	</Upload>
</template>

<script language="JavaScript">
	export default {
		props: {
			// 按钮标签
			label: {
				type: String,
				default: function() {
					return '上传';
				}
			},
			// 上传路径
			url: {
				type: String,
				default: function() {
					return '';
				}
			},
			// 是否显示上传列表
			showUploadList: {
				type: Boolean,
				default: function() {
					return false;
				}
			},
			// 接受文件类型
			accept: {
				type: String,
				default: function() {
					return '';
				}
			},
			data: {
				type: Object,
				default: function() {
					return {};
				}
			}
		},
		data() {
			return {
				headers: {}, // 请求头
			}
		},
		computed: {
			action: function() {
				return this.$config.baseUrl + this.url
			}
		},
		watch: {},
		created: function() {},
		mounted: function() {
			let token = localStorage.getItem(this.$config.tokenName)
			this.headers['Authorization'] = `bearer ${token}`
			this.headers['x-requested-with'] = 'XMLHttpRequest'
		},
		methods: {
			beforeUpload: function() {
				this.$Spin.show()
				this.$emit('before-upload')
			},
			onSuccess: function(res) {
				this.$Spin.hide()
				if (res.status == 'success') {
					this.$Message.success('上传成功')
					this.$emit('on-success', res)
				} else {
					this.$Notice.error({
						title: '上传出错',
						desc: res.message
					})
				}
			},
			onError: function() {
				this.$Spin.hide()
				this.$emit('on-error')
				this.$Message.error('上传错误')
			}
		}
	}
</script>

<style lang="scss" scoped="scoped">
</style>
